package com.fancy.social.service.impl;

import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fancy.imasclient.dto.FollowInfoDTO;
import com.fancy.imasclient.dto.FollowRequestDTO;
import com.fancy.social.dto.FollowDTO;
import com.fancy.social.entity.UserFollow;
import com.fancy.social.mapper.UserFollowMapper;
import com.fancy.social.service.FollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class FollowServiceImpl extends ServiceImpl<UserFollowMapper, UserFollow> implements FollowService {

    @Autowired
    private UserFollowMapper userFollowMapper;

    @Override
    @Transactional
    public void follow(Long userId, FollowDTO followDTO) {
        UserFollow userFollow = new UserFollow();
        userFollow.setFollowerId(userId);
        userFollow.setFollowingId(followDTO.getTargetId());
        userFollow.setFollowingType(followDTO.getTargetType());
        userFollow.setCreateTime(LocalDateTime.now());
        save(userFollow);
    }

    @Override
    @Transactional
    public void unfollow(Long userId, FollowDTO followDTO) {
        remove(new QueryWrapper<UserFollow>()
                .eq("follower_id", userId)
                .eq("following_id", followDTO.getTargetId())
                .eq("following_type", followDTO.getTargetType()));
    }

    @Override
    @Transactional
    public void followTarget(Long userId, FollowRequestDTO dto) {
        // 检查是否已经关注
        boolean exists = count(new QueryWrapper<UserFollow>()
                .eq("follower_id", userId)
                .eq("following_id", dto.getTargetId())
                .eq("following_type", dto.getTargetType())) > 0;

        if (exists) return;

        // 创建关注记录
        UserFollow userFollow = new UserFollow();
        userFollow.setFollowerId(userId);
        userFollow.setFollowingId(dto.getTargetId());
        userFollow.setFollowingType(dto.getTargetType());
        userFollow.setCreateTime(LocalDateTime.now());
        save(userFollow);
    }

    @Override
    @Transactional
    public void unfollowTarget(Long userId, FollowRequestDTO dto) {
        remove(new QueryWrapper<UserFollow>()
                .eq("follower_id", userId)
                .eq("following_id", dto.getTargetId())
                .eq("following_type", dto.getTargetType()));
    }

    @Override
    public PageResult<FollowInfoDTO> getFollowing(Long userId, int page, int size) {
        Page<FollowInfoDTO> pageParam = new Page<>(page, size);
        Page<FollowInfoDTO> result = userFollowMapper.selectFollowingPage(pageParam, userId);

        PageResult<FollowInfoDTO> pageResult = new PageResult<>();
        pageResult.setPage(page);
        pageResult.setPageSize(size);
        pageResult.setTotal((int) result.getTotal());
        pageResult.addAll(result.getRecords());

        return pageResult;
    }

    @Override
    public PageResult<FollowInfoDTO> getFollowers(Long userId, int page, int size) {
        Page<FollowInfoDTO> pageParam = new Page<>(page, size);
        Page<FollowInfoDTO> result = userFollowMapper.selectFollowersPage(pageParam, userId);

        PageResult<FollowInfoDTO> pageResult = new PageResult<>();
        pageResult.setPage(page);
        pageResult.setPageSize(size);
        pageResult.setTotal((int) result.getTotal());
        pageResult.addAll(result.getRecords());

        return pageResult;
    }

    @Override
    public Map<String, Object> getFollowStats(Long userId, Long currentUserId) {
        Map<String, Object> stats = new HashMap<>();

        // 1. 统计关注数量
        Long followingCount = count(new QueryWrapper<UserFollow>()
                .eq("follower_id", userId));

        // 2. 统计粉丝数量（用户类型）
        Long followerCount = count(new QueryWrapper<UserFollow>()
                .eq("following_id", userId)
                .eq("following_type", 1));

        // 3. 分类统计
        Long followingUsersCount = count(new QueryWrapper<UserFollow>()
                .eq("follower_id", userId)
                .eq("following_type", 1));

        Long followingArtistsCount = count(new QueryWrapper<UserFollow>()
                .eq("follower_id", userId)
                .eq("following_type", 2));

        // 4. 检查关注关系
        boolean isFollowed = false;
        boolean isFollowing = false;

        if (currentUserId != null && !currentUserId.equals(userId)) {
            isFollowed = count(new QueryWrapper<UserFollow>()
                    .eq("follower_id", currentUserId)
                    .eq("following_id", userId)
                    .eq("following_type", 1)) > 0;

            isFollowing = count(new QueryWrapper<UserFollow>()
                    .eq("follower_id", userId)
                    .eq("following_id", currentUserId)
                    .eq("following_type", 1)) > 0;
        }

        // 5. 返回结果
        stats.put("followingCount", followingCount);
        stats.put("followerCount", followerCount);
        stats.put("followingUsersCount", followingUsersCount);
        stats.put("followingArtistsCount", followingArtistsCount);
        stats.put("isFollowed", isFollowed);
        stats.put("isFollowing", isFollowing);
        stats.put("isMutualFollow", isFollowed && isFollowing);

        return stats;
    }
}